package com.example.demo.controller;

import com.example.demo.entity.News;
import com.example.demo.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.PostLoad;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/news")
@CrossOrigin
public class NewsController {

    @Autowired
    private NewsRepository newsRepository;


    @GetMapping("/findAll/{page}/{size}")
    public Page<News> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        return newsRepository.findAll(pageRequest);
    }

    @DeleteMapping("/deleteByid/{id}")
    public void delete(@PathVariable("id") Integer id) {
        newsRepository.deleteById(id);
    }

    @GetMapping("/findByid/{id}")
    public News findByid(@PathVariable("id") Integer id) {
        return newsRepository.findById(id).get();
    }

    @RequestMapping("/update")
    public void update(@RequestBody News news) {
        newsRepository.save(news);
    }

    @GetMapping("/search/{keywords}/{page}")
    public Page<News> getNewsList(@PathVariable("keywords") String keywords, @PathVariable ("page") Integer page){
        Pageable pageable = PageRequest.of(page,10, Sort.Direction.DESC, "id");
        return newsRepository.findNewsWithKeywords(keywords, pageable);

    }



}




